import { defineStore } from 'pinia';
import { ref } from 'vue';
import type { Message, ConnectionStatus } from './chat-types';
import { saveMessagesToStorage, loadMessagesFromStorage, getMessagesStorageKey, addDeletedMessageIds, getDeletedMessageIds } from './chat-storage';
import { createWebSocketHandlers } from './chat-websocket';
import { sendMessage } from './chat-message-sender';
import { setTarget, loadHistory, clearCurrentUserMessagesCache, clearUserMessages } from './chat-management';
import { createCurrentMessages } from './chat-computed';

export const useChatStore = defineStore('chat', () => {
  // 状态定义
  const currentUserId = ref<string | null>(null); // 存储 open_id（外部标识符），用于前端显示和消息存储
  const subscriptionId = ref<string | null>(null); // 存储订阅ID，用于WebSocket连接
  const currentTargetId = ref<string | null>(null); // 存储目标用户的 open_id 或用户名
  const targetType = ref<'User' | 'Group'>('User');
  const messages = ref<Message[]>([]);
  const isConnected = ref(false);
  const connectionStatus = ref<ConnectionStatus>('disconnected');

  // 存储相关功能包装
  const getMessagesStorageKeyWrapper = async (): Promise<string> => {
    return getMessagesStorageKey(currentUserId);
  };

  const saveMessagesToStorageWrapper = async () => {
    return saveMessagesToStorage(messages);
  };

  const loadMessagesFromStorageWrapper = async () => {
    return loadMessagesFromStorage(messages, currentUserId);
  };

  // 获取已删除消息ID列表的包装函数
  const getDeletedMessageIdsWrapper = async (): Promise<Set<string>> => {
    return getDeletedMessageIds(currentUserId);
  };

  // WebSocket 相关功能
  const { initWebSocket, connect, disconnect } = createWebSocketHandlers(
    isConnected,
    connectionStatus,
    currentUserId,
    subscriptionId,
    currentTargetId,
    targetType,
    messages,
    saveMessagesToStorageWrapper,
    loadMessagesFromStorageWrapper,
    getDeletedMessageIdsWrapper
  );

  // 消息发送功能
  const sendMessageWrapper = async (
    content: string,
    messageContentType: number = 1,
    fileName?: string,
    fileType?: string,
    fileUrl?: string,
    serverFileName?: string
  ) => {
    return sendMessage(
      content,
      messageContentType,
      fileName,
      fileType,
      currentUserId,
      currentTargetId,
      targetType,
      messages,
      saveMessagesToStorageWrapper,
      fileUrl,
      serverFileName
    );
  };

  // 聊天管理功能
  const setTargetWrapper = async (targetId: string, type: 'User' | 'Group' = 'User') => {
    return setTarget(targetId, type, currentTargetId, targetType);
  };

  const loadHistoryWrapper = async (targetId: string, before?: number) => {
    return loadHistory(targetId, before);
  };

  const clearCurrentUserMessagesCacheWrapper = async () => {
    return clearCurrentUserMessagesCache(messages);
  };

  const clearUserMessagesWrapper = async (targetUserId: string, alternativeIds?: string[]) => {
    return clearUserMessages(
      targetUserId,
      alternativeIds,
      messages,
      currentTargetId,
      currentUserId,
      getMessagesStorageKeyWrapper,
      saveMessagesToStorageWrapper
    );
  };

  // 删除选中的消息
  const deleteMessages = async (messageIds: string[]) => {
    if (messageIds.length === 0) return;
    
    // 从消息列表中删除
    const beforeCount = messages.value.length;
    messages.value = messages.value.filter(msg => !messageIds.includes(msg.message_id));
    const deletedCount = beforeCount - messages.value.length;
    
    if (deletedCount > 0) {
      // 将删除的消息ID添加到已删除列表（防止重新同步）
      await addDeletedMessageIds(messageIds, currentUserId);
      
      // 保存更新后的消息列表
      await saveMessagesToStorageWrapper();
      
      console.log(`已删除 ${deletedCount} 条消息，消息ID已添加到已删除列表`);
    }
    
    return deletedCount;
  };

  // 计算属性
  const currentMessages = createCurrentMessages(
    messages,
    currentTargetId,
    targetType,
    currentUserId
  );

  return {
    // 状态
    currentUserId,
    subscriptionId,
    currentTargetId,
    targetType,
    messages,
    isConnected,
    connectionStatus,
    
    // 计算属性
    currentMessages,
    
    // WebSocket 功能
    initWebSocket,
    connect,
    disconnect,
    
    // 消息功能
    sendMessage: sendMessageWrapper,
    
    // 聊天管理功能
    setTarget: setTargetWrapper,
    loadHistory: loadHistoryWrapper,
    
    // 存储功能
    saveMessagesToStorage: saveMessagesToStorageWrapper,
    loadMessagesFromStorage: loadMessagesFromStorageWrapper,
    
    // 清理功能
    clearCurrentUserMessagesCache: clearCurrentUserMessagesCacheWrapper,
    clearUserMessages: clearUserMessagesWrapper,
    deleteMessages,
  };
});
